package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.RefItem;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.group.DocRefGroup;
import org.akomantoso.core.io.util.group.TLCGroup;
import org.akomantoso.core.util.MapUtil;

/**
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 */
public final class RefItemUtil {

	private RefItemUtil() {
	}

	public static void read(Input in, List<RefItem> items) throws IOException {

		RefItem refItem = null;
		final String localName = in.getLocalName();
		
		while(true) {
			in.readNext();
			switch (in.getEventType()) {
			case InputConstants.START_ELEMENT:
				refItem = instantiate(in.getLocalName());
				refItem.readExternal(in);
				items.add(refItem);
				break;			
			case InputConstants.END_ELEMENT:
				if (localName.equals(in.getLocalName())) {
					return;
				} 
			}
		}

	}
	
	private static RefItem instantiate(String elementName) {
		final Instantiator<RefItem> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported for RefIem ?!?");
		}
		return instatiator.instantiate();
		
	}

	static final Map<String, Instantiator<RefItem>> MAP = new HashMap<String, Instantiator<RefItem>>();

	static {
		MapUtil.copy(TLCGroup.MAP,MAP);
		MapUtil.copy(DocRefGroup.MAP,MAP);
	}
	
	
}
